package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.model.Role;
import com.github.permissiondog.cancanpbackend.request.ApproverRequest;
import com.github.permissiondog.cancanpbackend.response.ApproverResponse;
import com.github.permissiondog.cancanpbackend.response.ApproversResponse;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.service.TemplateService;
import com.github.permissiondog.cancanpbackend.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "AdminApproverServlet", value = "/admin/template/approver")
public class AdminApproverServlet extends BaseServlet {
    /**
     * 创建审批人
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        var body = bind(req, res, ApproverRequest.class);
        if (body == null)   return;

        try {
            var approverUser = UserService.getInstance().getUserById(body.approverId);
            if (approverUser == null || !approverUser.getRole().equals(Role.APPROVER)) {
                json(res, BaseResponse.builder().ok(false).msg("不是合法的申请人").build());
                return;
            }

            var template = TemplateService.getInstance().getTemplateById(body.templateId);
            if (template == null) {
                json(res, BaseResponse.builder().ok(false).msg("未找到模板").build());
                return;
            }

            var approver = TemplateService.getInstance().addApprover(
                    body.templateId, body.approverId
            );
            json(res, ApproverResponse.builder().ok(true).approver(approver).build());
        } catch (Exception e) {
            json(res, BaseResponse.builder().ok(false).msg("创建失败").error(e.getMessage()).build());
        }
    }

    /**
     * 删除审批人
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException {
        var body = bind(req, res, ApproverRequest.class);
        if (body == null)   return;

        try {
            var ok = TemplateService.getInstance().deleteApprover(
                    body.templateId, body.approverId
            );
            if (!ok) {
                json(res, BaseResponse.builder().ok(false).msg("审批人不存在").build());
                return;
            }
        } catch (Exception e) {
            json(res, BaseResponse.builder().ok(false).msg("删除失败").error(e.getMessage()).build());
            return;
        }
        json(res, BaseResponse.builder().ok(true).build());
    }

}
